/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.secretaria.saude.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

/**
 *
 * @author pablo
 */
public class DoubleUtil {

    private static DecimalFormat df = new DecimalFormat();
    
    static {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator(',');
        symbols.setGroupingSeparator('.');
        df.setDecimalFormatSymbols(symbols);
        df.setDecimalSeparatorAlwaysShown(true);
        df.setRoundingMode(RoundingMode.HALF_EVEN);
    }

    public static String formatDecimal(Double decimal) {
        return formatDecimal(decimal, 2);
    }

    public static String formatDecimal(Double decimal, int decimais) {
        if (decimal == null) {
            return "";
        }
        df.setMinimumFractionDigits(decimais);
        df.setMaximumFractionDigits(decimais);
        return df.format(decimal);
    }

    public static double converterDouble(String numero) {
        String numeroSemVirgula = substituirPontuacao(numero);

        return Double.parseDouble(numeroSemVirgula);
    }

    private static String substituirPontuacao(String sinal) {
        String sinalFormatado;
        if (sinal.indexOf(",") >= 0) {
            sinalFormatado = sinal.replaceAll(",", ".");
        } else {
            sinalFormatado = sinal;
        }
        return sinalFormatado;
    }
}
